package com.yotoodesign.dianba.ui;

import java.util.ArrayList;
import java.util.Iterator;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yotoodesign.core.util.LoadImageAsynTask;
import com.yotoodesign.dianba.R;
import com.yotoodesign.dianba.bean.Song;
import com.yotoodesign.dianba.util.Constant;
import com.yotoodesign.dianba.util.SongService;

public class ShakeActivity extends Activity implements SensorEventListener{
	private Vibrator vibrator;
	private static final int SENSOR_SHAKE = 10;
	private SensorManager sensorManager;
	private MediaPlayer player;
	private TextView txtMsg,txtMsg2;
	private RelativeLayout shakeLayout;
	private ImageView ivAvatar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shake_songs);
		txtMsg = (TextView)findViewById(R.id.txtMsg);
		txtMsg2 = (TextView)findViewById(R.id.txtMsg2);
		shakeLayout = (RelativeLayout)findViewById(R.id.shakeLayout);
		ivAvatar = (ImageView)findViewById(R.id.ivAvatar);
		
		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); // 获取传感器管理服务
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); // 震动
		player = MediaPlayer.create(this, R.raw.shake);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (sensorManager != null) {// 注册监听器
			sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
			// 第一个参数是Listener，第二个参数是所得传感器类型，第三个参数值获取传感器信息的频率
		}
	}

	@Override
	protected void onStop() {
		sensorManager.unregisterListener(this);
		super.onStop();
		player.stop();
		Log.i("url", "player.stop()");
	}

	@Override
	protected void onPause() {
		sensorManager.unregisterListener(this);
		super.onPause();
	}
	

	Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case SENSOR_SHAKE:
				//检测到摇晃，开始操作
				txtMsg.setText("正在搜索歌曲...");
				showPanel(false,shakeLayout);
				break;
			}
		}
	};
	
	/*
	 * 显示面板
	 */
	private void showPanel(final boolean shown,View view){
		view.clearAnimation();
		
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int y1 = 0;
		int y2 = -dm.heightPixels;
		
		if(shown){
			y1= y2;
			y2 = 0;
		}
		
		TranslateAnimation ta = new TranslateAnimation(0,0,y1,y2);
		ta.setDuration(500);
		ta.setFillAfter(true);
		ta.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
			}
			@Override
			public void onAnimationRepeat(Animation animation) {
			}
			@Override
			public void onAnimationEnd(Animation animation) {
				if(shown==false){
					ArrayList list = SongService.getInstance().findRndSongsByTag("歌曲", 1);
					String songs = "";
					for(Iterator it = list.iterator();it.hasNext();){
						Song song = (Song)it.next();
						songs += song.getName()+"\n";
						txtMsg2.setText(songs);
						if(song.getSinger()!=null && song.getSinger().getImageUrl()!=null){
							LoadImageAsynTask.loadFromUrl(ivAvatar, song.getSinger().getImageUrl(), Constant.APP_DIR+"/"+Constant.IMAGE_CACHE);
						}else{
							ivAvatar.setImageBitmap(null);
						}
						//只取一条记录
						break;
					}
					
					
					
					showPanel(true,shakeLayout);
				}
			}
		});
		view.startAnimation(ta);
	}
	
	

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// 当传感器精度改变时回调该方法，Do nothing.
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		float[] values = event.values;
		float x = values[0];
		float y = values[1];
		float z = values[2];

		// 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。
		int medumValue = 19;
		if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) {
			try {
				player.start();
				player.setOnCompletionListener(new OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
						// TODO Auto-generated method stub
						player.pause();
						player.seekTo(0);
					}
				});
				
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
//			vibrator.vibrate(500);
			Message msg = new Message();
			msg.what = SENSOR_SHAKE;
			handler.sendMessage(msg);
		}
	}
}
